package com.atguigu.gmall.common.interceptor;


import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


public class FeignInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        //  任意位置获取当前微服务的请求对象
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes();
        if (null != servletRequestAttributes) {
            HttpServletRequest request = servletRequestAttributes.getRequest();
            if (null != request) {
                //将当前请求头中的用户ID 传递给即将远程调用的请求对象
                String userId = request.getHeader("userId");
                if (!StringUtils.isEmpty(userId)) {
                    requestTemplate.header("userId", userId);
                }
                String userTempId = request.getHeader("userTempId");
                if (!StringUtils.isEmpty(userTempId)) {
                    requestTemplate.header("userTempId", userTempId);
                }
            }
        }
    }

}
